package com.example.spring_config.util;

import com.example.spring_config.bean.LayuiTree;
import com.example.spring_config.mapper.Permission;
import java.util.ArrayList;
import java.util.List;

public class ToLayuiDataUtil {

    public static List<LayuiTree> PermissionArrayToLayui(List<Permission> permissionArrayList,List<String> pids){
        ArrayList<LayuiTree> layuiTrees = new ArrayList<>();
        for (int i = 0; i < permissionArrayList.size(); i++) {
            Permission permission = permissionArrayList.get(i);
            LayuiTree layuiTree;
            if(pids!=null && pids.contains(permission.getId())){
                layuiTree = PermissionArrayToLayui(permissionArrayList, permission, setData(permission, new LayuiTree(),true),pids);
            }else {
                layuiTree = PermissionArrayToLayui(permissionArrayList, permission, setData(permission, new LayuiTree(),false),pids);

            }
            if(permission.getPId().equals("")){
                layuiTrees.add(layuiTree);
            }
        }
        return layuiTrees;
    }

    /**
     * 把permission集合转换为LayuiTerr对象
     * @return
     */
    private static LayuiTree PermissionArrayToLayui(List<Permission> permissionArrayList,Permission permission,LayuiTree layuiTree,List<String> pids){
        for (int i = 0; i < permissionArrayList.size(); i++) {
            Permission permission1 = permissionArrayList.get(i);
            if(permission1.getPId().equals(permission.getId())){
                LayuiTree layuiTree1;
                if(pids!=null && pids.contains(permission1.getId())){
                    layuiTree1 = setData(permission1, new LayuiTree(),true);
                }else {
                    layuiTree1 = setData(permission1, new LayuiTree(),false);
                }

                if(layuiTree.getChildren()==null){
                    layuiTree.setChildren(new ArrayList<>());
                }
                layuiTree.getChildren().add(layuiTree1);
                PermissionArrayToLayui(permissionArrayList,permission1,layuiTree1,pids);
            }
        }
        return layuiTree;
    }

    private static LayuiTree setData(Permission permission,LayuiTree layuiTree,boolean flag){
        layuiTree.setTitle(permission.getName());
        layuiTree.setId(permission.getId());
        layuiTree.setName(permission.getName());
        layuiTree.setValue(permission.getId());
        if(flag){
            layuiTree.setSelected(true);
        }
        return layuiTree;
    }



}
